// 客户端
const prisma = require('./prisma')

// 从结果集中筛选,不包括哪些字段
const omitFields = {
  updated_at: true, //
  deleted_at: true,
}

class LogModel {
  async create(log) {
    return await prisma.log.create({
      data: {
        req_id: log.req_id,
        module: log.module ? log.module : '',
        level: log.level ? log.level : '',
        note: log.note ? log.note : '',
        body: log.body ? log.body : '',
        owner_id: log.owner_id ? log.owner_id : 1,
      },
      omit: omitFields,
    })
  }
  //
  async get(id, where = null) {
    // select 与 include 不能同时使用
    const result = await prisma.log.findFirst({
      where: Object.assign({ id: id }, where),
      // 从结果集中过滤，不包括某些字段
      omit: omitFields, // 不能与select同时使用
    })
    return result
  }
  // 列表 这里官方建议使用游标
  async list(pageNo, pageSize, where = null) {
    //
    const skip = (pageNo - 1) * pageSize
    return await prisma.log.findMany({
      omit: omitFields,
      skip: skip,
      take: pageSize,
      orderBy: {
        id: 'desc',
      },
      where: Object.assign({}, where),
    })
  }

  // 未删除的数据
  async count(where = null) {
    return await prisma.log.count({
      where: Object.assign({}, where),
    })
  }

  // 更新
  async update(id, proj, where = null) {
    return await prisma.log.update({
      omit: omitFields,
      where: Object.assign({ id: id }, where),
      data: proj,
    })
  }

  // 删除
  async del(id, where = null) {
    return await prisma.log.update({
      data: {
        deleted_at: new Date(), // 逻辑删除
      },
      omit: omitFields,
      where: Object.assign({ id: id }, where),
    })
  }

  async modules(owner_id) {
    return await prisma.log.findMany({
      distinct: ['module'],
      omit: {
        id: true,
        req_id: true,
        level: true,
        note: true,
        body: true,
        owner_id: true,
        created_at: true,
        updated_at: true,
        deleted_at: true,
      },
      where: {
        owner_id: owner_id,
      },
    })
  }
  async levels(owner_id, module) {
    return await prisma.log.findMany({
      distinct: ['level'],
      omit: {
        id: true,
        req_id: true,
        module: true,
        note: true,
        body: true,
        owner_id: true,
        created_at: true,
        updated_at: true,
        deleted_at: true,
      },
      where: {
        owner_id: owner_id,
        module: module,
      },
    })
  }
}

module.exports = new LogModel()
